package com.cool.modules.finance.service.statistics;

import com.cool.core.exception.CoolException;
import com.cool.core.util.CoolSecurityUtil;
import com.cool.modules.finance.service.family.FinanceUserFamilyService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public abstract class FinanceStatisticsBase {

    @Autowired
    protected FinanceUserFamilyService userFamilyService;


    /**
     * 获取家庭id
     * @return
     */
    protected Long getFamilyId(){
        Long familyId = userFamilyService.getFamilyIdByUserId(CoolSecurityUtil.getCurrentUserId());
        if (null==familyId) throw new CoolException("当前用户没有绑定家庭，请先绑定家庭再试");
        return familyId;
    }

    /**
     * 获取家庭成员id
     * @return
     */
    protected List<Long> getFamilyUserIds(){
        List<Long> familyUserIdsByUserId = userFamilyService.getFamilyUserIdsByUserId(CoolSecurityUtil.getCurrentUserId());
        if (null==familyUserIdsByUserId) throw new CoolException("当前用户没有绑定家庭，请先绑定家庭再试");
        return familyUserIdsByUserId;
    }

    /**
     * 获取当月1号的日期
     *
     * @return 当月1号的日期
     */
    protected Date getFirstDayOfCurrentMonth() {
        LocalDate today = LocalDate.now();
        return convertLocalDateToDate(today.withDayOfMonth(1));
    }

    /**
     * 获取下月1号的日期
     *
     * @return 下月1号的日期
     */
    protected Date getFirstDayOfNextMonth() {
        LocalDate today = LocalDate.now();
        YearMonth nextMonth = YearMonth.from(today).plusMonths(1);
        return convertLocalDateToDate(nextMonth.atDay(1));
    }

    /**
     * 将LocalDate转换为Date
     * @param localDate
     * @return
     */
    private Date convertLocalDateToDate(LocalDate localDate) {
        Date from = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(from);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取当月天数
     * @return
     */
    protected int getDaysInCurrentMonth() {
        LocalDate currentDate = LocalDate.now();
        YearMonth yearMonth = YearMonth.from(currentDate);
        return yearMonth.lengthOfMonth();
    }

    /**
     * 获取当月月份
     * @return
     */
    protected Integer getCurrentMonth() {
        LocalDate currentDate = LocalDate.now();
        return currentDate.getMonthValue();
    }


}
